package com.rainng.coursesystem.module.task.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainng.coursesystem.base.api.dto.BaseIdsReqDTO;
import com.rainng.coursesystem.base.api.dto.PagingReqDTO;
import com.rainng.coursesystem.base.utils.BeanMapper;
import com.rainng.coursesystem.dao.mapper.TireInfoMapper;
import com.rainng.coursesystem.dao.mapper.UserGroupMapper;
import com.rainng.coursesystem.model.entity.CodeWhiteEntity;
import com.rainng.coursesystem.model.excelvo.TaskExcelVo;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.module.custom.entity.Custom;
import com.rainng.coursesystem.module.custom.mapper.CustomMapper;
import com.rainng.coursesystem.module.custom.service.CustomService;
import com.rainng.coursesystem.module.system.entity.SysGroup;
import com.rainng.coursesystem.module.system.entity.SysUser;
import com.rainng.coursesystem.module.system.service.SysGroupService;
import com.rainng.coursesystem.module.system.service.SysUserService;
import com.rainng.coursesystem.module.task.dto.request.*;
import com.rainng.coursesystem.module.task.dto.response.CarProjectResDTO;
import com.rainng.coursesystem.module.task.dto.response.CodeWhiteListResDTO;
import com.rainng.coursesystem.module.task.dto.response.TaskCarResDTO;
import com.rainng.coursesystem.module.task.dto.response.TaskPagingResDTO;
import com.rainng.coursesystem.module.task.entity.Task;
import com.rainng.coursesystem.module.task.entity.projectEntity;
import com.rainng.coursesystem.module.task.mapper.TaskMapper;
import com.rainng.coursesystem.module.task.service.BatchService;
import com.rainng.coursesystem.module.task.service.TaskService;
import com.rainng.coursesystem.service.TireInfoService;
import com.rainng.coursesystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.rainng.coursesystem.model.entity.CodeWhiteEntity;
import com.rainng.coursesystem.module.task.dto.request.CodeWhiteListDTO;
import com.rainng.coursesystem.module.task.dto.request.TaskCarDTO;
import com.rainng.coursesystem.module.task.dto.request.TaskConfigDTO;
import com.rainng.coursesystem.module.task.dto.request.StRuleListDTO;
import com.rainng.coursesystem.module.task.entity.TaskChangeVo;
import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private CustomService customService;

    @Resource
    private UserService userService;

    @Resource
    private SysGroupService sysGroupService;

    @Resource
    private BatchService batchService;

    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private CustomMapper customMapper;


    @Resource
    private TireInfoMapper tireInfoMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TireInfoService tireInfoService;
    @Override
    public void saveTasks(List<TaskExcelVo> vos) {

        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        log.warn("开始新增任务！");
        for (TaskExcelVo o : vos) {
            if (o == null || o.getApplyNum() == null || o.getApplyNum().trim().isEmpty()) {
                log.warn("跳过空行或无效数据！");
                continue;
            }

            //根据userName找userId
            String userId = userGroupMapper.getUserIdByRealName(o.getUserName());
            //根据customName找customId
            List<String> customIds = customMapper.getCustomIdByCustomName(o.getCustomName());
            TaskDetailDTO reqDto = new TaskDetailDTO();
            BeanUtil.copyProperties(o, reqDto);//第一个参数向第二个赋值

            Task task = new Task();
            BeanUtil.copyProperties(o, task);
            task.setUserId(userId);
            if (CollectionUtil.isNotEmpty(customIds)) {
                task.setCustomId(customIds.get(0));
            }

            if (task.getId() == null || task.getId() == "" || task.getId().isEmpty()) {
                if (task.getApplyNum() != null) {
                    List<Task> list = baseMapper.selectList(new LambdaQueryWrapper<Task>().eq(Task::getApplyNum, reqDto.getApplyNum()));
                    if (list.size() > 0) {
                        log.warn("新增任务失败，申请编号重复！");
                        continue;
                    }
                }
                task.setId(IdWorker.getIdStr());
                task.setCreateBy(username);
                Date date = new Date();
                long timestamp = date.getTime();
                task.setCreateTime(date);
                task.setCreatetimelong(timestamp);
                this.save(task);
                if (task.getTaskType().equals("变更扩展")) {
                    TaskChangeVo taskChangeVo = new TaskChangeVo();
                    taskChangeVo.setTaskName(task.getTaskName());
                    taskChangeVo.setBatchId(task.getBatchId());
                    taskChangeVo.setFapplyNum(task.getApplyNum());
                    taskChangeVo.setTaskType(task.getTaskType());
                    taskChangeVo.setCustomId(task.getCustomId());
                    taskChangeVo.setUserId(task.getUserId());
                    taskChangeVo.setVeModel(task.getVeModel());
                    taskChangeVo.setVeType(task.getVeType());
                    taskChangeVo.setRemark(task.getRemark());
                    tireInfoService.editTaskChange(taskChangeVo);
                }
                save(reqDto);
            }
        }
    }


    @Override
    public List<CarProjectResDTO> getCarprojectList(String taskCode, String vin) {
        List<CarProjectResDTO> carprojectList= baseMapper.getcarpro(taskCode,vin);
        return carprojectList;
    }

    @Override
    public int deleteTaskChangeByFatherIds(List<String> ids) {

        List<String> fatherapplynums = tireInfoMapper.selectTaskApplyNumByIds(ids);
        int j = tireInfoMapper.deleteTaskChangeByFatherApplyNums(fatherapplynums);
        return j;
    }

    @Override
    public projectEntity getProject(String veType, Integer prjNum) {
        projectEntity prj=baseMapper.getproject(veType,prjNum);
        return prj;
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public ResultVO save(TaskDetailDTO reqDto) {
        Task task = new Task();
        BeanMapper.copy(reqDto, task);
        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        String username = vo.getData().get("username");
        if (task.getId() == null || task.getId() == "") {
            if (task.getApplyNum() != null) {
                List<Task> list = baseMapper.selectList(new LambdaQueryWrapper<Task>().eq(Task::getApplyNum, reqDto.getApplyNum()));
                if (list.size() > 0) {
                    //throw new ServiceException("新增任务失败，申请编号重复！");
                    return new ResultVO(ResultVO.FAIL, "新增任务失败，申请编号重复！", "");
                }
            }
            Date date = new Date();
            long timestamp = date.getTime();
            task.setCreateTime(date);
            task.setCreatetimelong(timestamp);
            task.setId(IdWorker.getIdStr());
            task.setCreateBy(username);
            this.save(task);
        } else {
            Date date = new Date();
            long timestamp = date.getTime();
            task.setCreateTime(date);
            task.setCreatetimelong(timestamp);
            task.setCreateBy(username);
            this.updateById(task);
        }
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    @Override
    public ResultVO setTaskImportant(TaskDetailDTO reqDto) {
        int isImportant = reqDto.getIsImportant();

        tireInfoMapper.setTaskImportant(reqDto.getId(), isImportant);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    @Override
    public ResultVO saveCodeWhiteList(CodeWhiteEntity reqDto) {
        taskMapper.saveCodeWhiteList(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO updateCodeWhiteList(CodeWhiteEntity reqDto) {
        taskMapper.updateCodeWhiteList(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO deleteCodeWhiteList(CodeWhiteEntity reqDto) {
        taskMapper.deleteCodeWhiteList(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    @Override
    public IPage<CodeWhiteListResDTO> getCodeWhiteList(PagingReqDTO<CodeWhiteListDTO> reqDTO) {
        IPage<CodeWhiteListResDTO> res;
        res = baseMapper.getCodeWhiteList(reqDTO.toPage(), reqDTO.getParams());
        return res;
    }
    public ResultVO saveTaskConfig(TaskConfigDTO reqDto) {
        taskMapper.saveTaskConfig(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO updateTaskConfig(TaskConfigDTO reqDto) {
        taskMapper.updateTaskConfig(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public TaskConfigDTO getTaskConfig(String taskCode) {
        return taskMapper.getTaskConfig(taskCode);
    }
    public ResultVO saveTaskCar(TaskCarDTO reqDto) {
        taskMapper.saveTaskCar(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO updateTaskCar(TaskCarDTO reqDto) {
        taskMapper.updateTaskCar(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
/*    public List<TaskExportReqDTO> getTaskListByIds(BaseIdsReqDTO reqDTO) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Task::getId, reqDTO.getIds());
        List<Task> tasks = baseMapper.selectList(wrapper);
        return getAllTask(tasks);
    }*/

    public List<TaskCarResDTO> getTaskCarByTaskCode(String applyNum) {
        List<TaskCarResDTO> res;
        res = taskMapper.getTaskCarByApplyNum(applyNum);
        return res;
    };
    public List<TaskCarResDTO> getCarList(String taskCode) {
        List<TaskCarResDTO> res=new ArrayList<TaskCarResDTO>();
        List<TaskCarResDTO> initialData = taskMapper.getCarList(taskCode);
        //获取初始化数据之后进行处理在获取对应的项目信息
        for(TaskCarResDTO it:initialData){
            String vin=it.getVin();
            List<CarProjectResDTO> list= getCarprojectList(taskCode,vin);
            if(list.size()>0){
                CarProjectResDTO car= (CarProjectResDTO)list.get(0);
                //获取配置列表里面car的key值
                Integer carindex= Integer.parseInt(car.getAllConfigIndex());
                String veType=car.getVeType();
                JSONArray ja=new JSONArray(car.getConfigs());
                List<Map<String,String>> projectLis=new ArrayList<>();
                for(Object ob:ja){
                    JSONObject item=new JSONObject(ob);
                    Object key= item.get("key");
                    if(key==carindex){
                        String pr=item.get("pr").toString();
                        it.setProjects(pr);
                        res.add(it);

                    }
                }
            }

        }

        return res;
    };
    public List<TaskCarResDTO> getCarListByVIN(String vin, String taskCode) {
        List<TaskCarResDTO> res;
        res = taskMapper.getCarListByVIN(vin, taskCode);
        return res;
    };
    public TaskCarResDTO getTaskCarDetail(String configIndex, String taskCode) {
        return taskMapper.getTaskCarDetail(configIndex, taskCode);
    };

    public IPage<StRuleListDTO> getStRuleList(PagingReqDTO<StRuleListDTO> reqDTO) {
        IPage<StRuleListDTO> res;
        res = baseMapper.getStRuleList(reqDTO.toPage(), reqDTO.getParams());
        return res;
    }
    public ResultVO saveStRuleList(StRuleListDTO reqDto) {
        taskMapper.saveStRuleList(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO updateStRule(StRuleListDTO reqDto) {
        taskMapper.updateStRule(reqDto);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    public ResultVO deleteStRule(String id) {
        taskMapper.deleteStRule(id);
        return new ResultVO(ResultVO.SUCCESS, "success", "");
    }
    @Override
    public IPage<TaskPagingResDTO> paging(PagingReqDTO<TaskQueryReqDTO> reqDTO) {

        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        if (StrUtil.isEmpty(reqDTO.getParams().getBatchId())) {
            if(StrUtil.isEmpty(reqDTO.getParams().getApplyNum())
                    && StrUtil.isEmpty(reqDTO.getParams().getCompany())
//                    && StrUtil.isEmpty(reqDTO.getParams().getNumId())
                    && StrUtil.isEmpty(reqDTO.getParams().getRealName())
                    && StrUtil.isEmpty(reqDTO.getParams().getTaskCode())
                    && StrUtil.isEmpty(reqDTO.getParams().getVeModel())
                    && StrUtil.isEmpty(reqDTO.getParams().getVeType())
            ){

                System.out.print((reqDTO.getParams().getNumId()));
                /*if(!" ".equals(reqDTO.getParams().getNumId()) && reqDTO.getParams().getNumId() == null){
                    String ba = batchService.getThisBatchName();
                    reqDTO.getParams().setBatchId(ba);
                }*/


            }
        }
        String username = vo.getData().get("username");
        String groupName = vo.getData().get("groupName");
        String roleName = vo.getData().get("roleName");
        String userId = String.valueOf(vo.getData().get("uId"));
        log.info(vo.toString());
        reqDTO.getParams().setCreateBy(username);
        reqDTO.getParams().setUserId(userId);
        reqDTO.getParams().setRoleName(roleName);
        reqDTO.getParams().setGroupName(groupName);
        IPage<TaskPagingResDTO> res = null;
        String userType = String.valueOf(vo.getData().get("userType"));

        //1.超级管理员拿到所有数据
        if ("3".equals(userType)) {
            if ("".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);//前台第一次传null第二次为""
            }
            if ("待录入".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);
            }
            if (" ".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId("");
            }
//            String VV= reqDTO.toPage();
            res = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }
        //7.企业
        if ("7".equals(userType)) {
            if ("".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);//前台第一次传null第二次为""
            }
            if ("待录入".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);
            }
            //根据查询企业
            String uname = vo.getData().get("username");
            if(StrUtil.isNotEmpty(uname)){
                List<String> c = customMapper.getCompanyNameByUserName(uname);
                if(c.size() > 0){
                    reqDTO.getParams().setCompany(c.get(0));
                }
            }else{
                reqDTO.getParams().setCompany(" ");
            }

            res = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }

        else if ("4".equals(userType)) {
            if ("".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);//前台第一次传null第二次为""
            }
            if ("待录入".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId("");
            }

            res = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        } else if ("2".equals(userType)) {
            if ("".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);
            }
            if ("待录入".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId("");
            }

            //3.组长角色,能够看到一个组内的信息
            res = baseMapper.pagingByGroup(reqDTO.toPage(), reqDTO.getParams());
            return res;
        } else if ("1".equals(userType)) {
            if ("".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId(null);
            }
            if ("待录入".equals(reqDTO.getParams().getNumId())) {
                reqDTO.getParams().setNumId("");
            }
            //2.主检也只能看到主检等于自己的数据并且属于一个组
            res = baseMapper.pagingByPerson(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }
        return res;
    }
    public IPage<TaskPagingResDTO> taskChangePaging(PagingReqDTO<TaskQueryReqDTO> reqDTO) {

        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        if (StrUtil.isEmpty(reqDTO.getParams().getBatchId())) {
            if(StrUtil.isEmpty(reqDTO.getParams().getApplyNum())
                    && StrUtil.isEmpty(reqDTO.getParams().getCompany())
//                    && StrUtil.isEmpty(reqDTO.getParams().getNumId())
                    && StrUtil.isEmpty(reqDTO.getParams().getRealName())
                    && StrUtil.isEmpty(reqDTO.getParams().getTaskCode())
                    && StrUtil.isEmpty(reqDTO.getParams().getVeModel())
                    && StrUtil.isEmpty(reqDTO.getParams().getVeType())
            ){

                System.out.print((reqDTO.getParams().getNumId()));
                /*if(!" ".equals(reqDTO.getParams().getNumId()) && reqDTO.getParams().getNumId() == null){
                    String ba = batchService.getThisBatchName();
                    reqDTO.getParams().setBatchId(ba);
                }*/


            }
        }
        String username = vo.getData().get("username");
        String groupName = vo.getData().get("groupName");
        String roleName = vo.getData().get("roleName");
        String userId = String.valueOf(vo.getData().get("uId"));
        log.info(vo.toString());
        reqDTO.getParams().setCreateBy(username);
        reqDTO.getParams().setUserId(userId);
        reqDTO.getParams().setRoleName(roleName);
        reqDTO.getParams().setGroupName(groupName);
        IPage<TaskPagingResDTO> res = null;
        String userType = String.valueOf(vo.getData().get("userType"));

        //1.超级管理员拿到所有数据
        if ("3".equals(userType)) {
//            String VV= reqDTO.toPage();
            res = baseMapper.taskChangePaging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }
        //7.企业
        if ("7".equals(userType)) {
            //根据查询企业
            String uname = vo.getData().get("username");
            if(StrUtil.isNotEmpty(uname)){
                List<String> c = customMapper.getCompanyNameByUserName(uname);
                if(c.size() > 0){
                    reqDTO.getParams().setCompany(c.get(0));
                }
            }else{
                reqDTO.getParams().setCompany(" ");
            }

            res = baseMapper.taskChangePaging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }

        else if ("4".equals(userType)) {
            res = baseMapper.taskChangePaging(reqDTO.toPage(), reqDTO.getParams());
            return res;
        } else if ("2".equals(userType)) {
            //3.组长角色,能够看到一个组内的信息
            res = baseMapper.taskChangePagingByGroup(reqDTO.toPage(), reqDTO.getParams());
            return res;
        } else if ("1".equals(userType)) {
            //2.主检也只能看到主检等于自己的数据并且属于一个组
            res = baseMapper.taskChangePagingByPerson(reqDTO.toPage(), reqDTO.getParams());
            return res;
        }
        return res;
    }

    @Override
    public TaskPagingResDTO detail(String id) {
        Task task = this.getById(id);
        TaskPagingResDTO resDTO = new TaskPagingResDTO();
        if (task == null) return resDTO;
        BeanMapper.copy(task, resDTO);
        if (task.getCustomId() != null) {
            Custom custom = customService.getById(task.getCustomId());
            if (custom != null) {
                resDTO.setCusName(custom.getCusName());
                resDTO.setArea(custom.getArea());
                resDTO.setProvince(custom.getProvince());
                resDTO.setCity(custom.getCity());
            }
        }
        if (task.getUserId() != null) {

            SysUser user = sysUserService.getById(task.getUserId());
            if (user != null) {
                resDTO.setUserName(user.getUserName());
                SysGroup group = sysGroupService.getById(user.getGroupId());
                if (group != null) resDTO.setGroupName(group.getGroupName());
            }
        }
        return resDTO;
    }

    @Override
    public List<TaskExportReqDTO> getTaskListByIds(BaseIdsReqDTO reqDTO) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Task::getId, reqDTO.getIds());
        List<Task> tasks = baseMapper.selectList(wrapper);
        return getAllTask(tasks);
    }

    @Override
    public List<TaskExportReqDTO> getAllTask() {
        List<Task> tasks = this.list();
        return getAllTask(tasks);
    }

    @Override
    public List<GroupTaskExportReqDTO> getTaskByAdmin() {
        List<Map<String, Object>> mapList = baseMapper.getAllInfo();
        //拿到所有组
        List<String> groups = baseMapper.getAllGroupsName();

        List<GroupTaskExportReqDTO> res = new ArrayList<>();
        for (String g : groups) {
            GroupTaskExportReqDTO po = new GroupTaskExportReqDTO();
            po.setGroupName(g);
            Integer newtotal = baseMapper.countByTaskType("新产品", g, null, null);
            Integer changtotal = baseMapper.countByTaskType("变更扩展", g, null, null);
            Integer alltotal = newtotal + changtotal;
            if (alltotal == 0) {
                continue;
            }

            po.setChange(changtotal.toString());
            po.setNewProduct(newtotal.toString());
            po.setTotal(alltotal.toString());

            res.add(po);
            //查询组下所有users
            List<String> users = baseMapper.getAllUsersByGroupName(g);
            for (String user : users) {
                GroupTaskExportReqDTO upo = new GroupTaskExportReqDTO();
                upo.setUserName(user);
                po.setGroupName(g);
                Integer unewtotal = baseMapper.countByTaskType("新产品", g, user, null);
                Integer uchangtotal = baseMapper.countByTaskType("变更扩展", g, user, null);
                Integer ualltotal = unewtotal + uchangtotal;
                upo.setChange(uchangtotal.toString());

                upo.setNewProduct(unewtotal.toString());
                if (unewtotal == 0) {
                    upo.setNewProduct("");
                }
                if (uchangtotal == 0) {
                    upo.setChange("");
                }
                upo.setTotal(ualltotal.toString());
                res.add(upo);

                //三for循环先这样吧,根据group和user查询所有company
                List<String> comps = baseMapper.getAllCompanyByGroupNameAndUserName(g, user);
                for (String c : comps) {
                    GroupTaskExportReqDTO cpo = new GroupTaskExportReqDTO();
                    cpo.setCompany(c);
                    Integer cnewtotal = baseMapper.countByTaskType("新产品", g, user, c);
                    Integer cchangtotal = baseMapper.countByTaskType("变更扩展", g, user, c);
                    Integer calltotal = cnewtotal + cchangtotal;
                    cpo.setChange(cchangtotal.toString());

                    cpo.setNewProduct(cnewtotal.toString());
                    if (cnewtotal == 0) {
                        cpo.setNewProduct("");
                    }
                    if (cchangtotal == 0) {
                        cpo.setChange("");
                    }
                    cpo.setTotal(calltotal.toString());
                    res.add(cpo);
                }


            }


//            List<Map<String,Object>> mapgroups = baseMapper.getInfoByGroupName(g);
//            GroupTaskExportReqDTO gpo = new GroupTaskExportReqDTO();
//            Integer grouptotal = 0;
//            for(Map<String,Object> mg : mapgroups){
//                if("变更扩展".equals(mg.get("taskType").toString())){
//                    gpo.setChange(mg.get("num").toString());
//                    grouptotal = grouptotal + Integer.valueOf(mg.get("num").toString()).intValue();
//                }
//                if("新产品".equals(mg.get("taskType").toString())){
//                    gpo.setNewProduct(mg.get("num").toString());
//                    grouptotal = grouptotal + Integer.valueOf(mg.get("num").toString()).intValue();
//                }
//            }
//            gpo.setTotal(grouptotal.toString());
//            res.add(gpo);

        }
        //总计行
        GroupTaskExportReqDTO total = new GroupTaskExportReqDTO();
        total.setGroupName("总计");
        Integer newtotal = baseMapper.countByTaskType("新产品", null, null, null);
        Integer changtotal = baseMapper.countByTaskType("变更扩展", null, null, null);
        Integer alltotal = newtotal + changtotal;
        total.setChange(changtotal.toString());
        total.setNewProduct(newtotal.toString());
        total.setTotal(alltotal.toString());


        res.add(total);
        return res;
    }


    /**
     * 用于封装导出数据
     *
     * @param tasks
     * @return
     */
    public List<TaskExportReqDTO> getAllTask(List<Task> tasks) {
        List<TaskExportReqDTO> req = new ArrayList<>();
        TaskExportReqDTO dto = null;
        ResultVO<Map<String, String>> vo = userService.getLoginStatusWithDepartment();
        String roleId = String.valueOf(vo.getData().get("userType"));
        for (Task task : tasks) {
            dto = new TaskExportReqDTO();
            BeanMapper.copy(task, dto);
            /**
             * 非管理员用户,导出时不能携带n_id
             */
            if (!"3".equals(roleId)) {
                dto.setNumId(null);
            }
            if (task.getUserId() != null) {
                SysUser user = sysUserService.getById(task.getUserId());
                if (user != null) {
                    dto.setUserName(user.getRealName());
                    SysGroup group = sysGroupService.getById(user.getGroupId());
                    if (group != null) {
                        dto.setGroupName(group.getGroupName());
                    }
                }
            }
            if (task.getCustomId() != null) {
                Custom custom = customService.getById(task.getCustomId());
                if (custom != null) {
                    dto.setCusName(custom.getComName());
                    dto.setArea(custom.getArea());
                    dto.setProvince(custom.getProvince());
                    dto.setCity(custom.getCity());
                }
            }
            req.add(dto);
        }
        return req;
    }

}
